package com.jilefojing.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jilefojing.beans.constant.Constants;
import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.response.base.ResponseData;
import com.jilefojing.beans.data.web.request.LoginRequest;
import com.jilefojing.beans.enums.PlatformEnum;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.enhanced.EnhancedUser;
import com.jilefojing.beans.pojos.enhanced.EnhancedUserSession;
import com.jilefojing.context.beans.vo.RememberMe;
import com.jilefojing.context.beans.vo.UserToken;
import com.jilefojing.service.IUserService;
import com.jilefojing.session.service.ILoginService;
import com.jilefojing.session.service.IUserContextService;
import com.jilefojing.util.UserTokenUtil;
import com.jilefojing.web.base.BaseWeb;
import com.octo.captcha.service.multitype.MultiTypeCaptchaService;

@Controller
@RequestMapping("login")
public class LoginWeb extends BaseWeb {

	@Autowired
	private MultiTypeCaptchaService captchaService;
	@Autowired
	private ILoginService loginService;
	@Autowired
	private IUserContextService userContextService;
	@Autowired
	private IUserService userService;

	private static final Logger _LOGGER = LoggerFactory.getLogger(LoginWeb.class);

	/**
	 * 登录接口
	 * 
	 * @param loginRequest
	 * @param request
	 * @return
	 */
	@RequestMapping("")
	public @ResponseBody ResponseData login(LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
		ResponseData responseData = new ResponseData();

		Boolean isResponseCorrect = captchaService.validateResponseForID(request.getSession().getId(), loginRequest.getValidataImg());
		if (!isResponseCorrect) {
			responseData.setResponseEnum(ResponseEnum.IMG_VALIDATA_ERROR);
			return responseData;
		}

		try {
			EnhancedUserSession enhancedUserSession = loginService.loginWithPassword(loginRequest.getTelphone(), loginRequest.getPassword(), true, null, PlatformEnum.PC, null,
					loginRequest.isRemember(), null);

			EnhancedUser enhancedUserInfo = userService.getEnhancedUser(enhancedUserSession.getEnhancedUser().getId());

			EnhancedUser _sessionEnhancedUser = null;
			if (loginRequest.isRemember()) {
				_sessionEnhancedUser = new EnhancedUser();
				_sessionEnhancedUser.setId(enhancedUserInfo.getId());
				_sessionEnhancedUser.setPassword(enhancedUserInfo.getPassword());
			} else {
				_sessionEnhancedUser = new EnhancedUser();
				_sessionEnhancedUser.setId(enhancedUserInfo.getId());
			}

			enhancedUserSession.setEnhancedUser(_sessionEnhancedUser);

			UserToken userToken = new UserToken(enhancedUserSession);
			RememberMe rememberMe = null;
			try {
				rememberMe = UserTokenUtil.generateRememberMe(enhancedUserSession);
				rememberMe.setRm(loginRequest.isRemember());
			} catch (Exception e) {
				_LOGGER.error("[生成REMEMBERME异常]:" + e.getMessage(), e);
			}
			userToken.setRm(rememberMe);

			UserTokenUtil.writeUserTokenToCookie(userToken, response);

			request.setAttribute(Constants.USER_CONTEXT_KEY, userContextService.loadUserContext(enhancedUserSession.getEnhancedUser().getId(), super.getServerTypeEnum()));

		} catch (UserContextException e) {
			_LOGGER.error("登录异常", e);
			responseData.setResponseEnum(e.getResponse());
			return responseData;
		}
		return responseData;

	}

	@RequestMapping("page.html")
	public String loginPage() {
		try {
			if (super.getUserContext() != null) {
				return super.redirect("/");
			}
		} catch (UserContextException e) {
			// 此异常暂时可以忽略
		}
		return "/web/login";
	}

}
